<?php    
    // Don't show warnings
    error_reporting(E_ALL ^ E_WARNING);

    // Check for required values
    if(!isset($_REQUEST['user']) || !isset($_REQUEST['passwd']) )
    {
        header('Location:index.php?status=EXP');
        die();
    }

	$user = $_REQUEST['user'];
	$pass = $_REQUEST['passwd'];

    // Get DB conection
    include "DB_connect.php";

    // Avoid SQL injection
    $user = mysqli_real_escape_string($data_base_conection, $user);
    $pass = mysqli_real_escape_string($data_base_conection, $pass);

	if((strlen($user) == 0) || (strlen($pass) == 0))
    {
		header('Location:index.php?status=FAILED');
        die();
    }

    // Check for the user in DB
    $consultaSQL = "SELECT * FROM usuario WHERE username = '$user' AND password = md5('$pass')";
    $result = mysqli_query($data_base_conection, $consultaSQL);
    if($result == FALSE)
    {
        header('Location:index.php?status=CFAILED');
        die();
    }
    $registro = mysqli_fetch_array($result);
    if($registro)
    {
        session_start();
        $_SESSION['user_id']          = $registro['ID'];
        $_SESSION['user_tipo']        = $registro['ID_tipoUsuario'];
        $_SESSION['user_name']        = $registro['nombre'];
        $_SESSION['user_apellidoP']   = $registro['apellidoP'];
        $_SESSION['user_apellidoM']   = $registro['apellidoM'];

        // Dependiendo del tipo de usuario, se va al menú indicado
        /*
        if($registro['ID_tipoUsuario'] == 1)
        {
            header('Location:menuDirectivo.php');
        }
        else
        {
            header('Location:menuAdmin.php');
        }

        // Fin
        die();
        */
        
        switch ($registro['ID_tipoUsuario']) {
            case 1:
                header('Location:menuDirectivo.php');
                break;
            case 2:
                header('Location:menuProveedor.php');
                break;
            case 3:
                header('Location:menuPM.php');
                break;
            case 4:
                header('Location:menuEC.php');
                break;
            case 5:
                header('Location:menuRecurso.php');
                break;
            case 6:
                header('Location:menuAdmin.php');
                break;
}

        die();
        
    }
    else
    {
        header('Location:index.php?status=FAILED');
        die();
    }
?>
